# coding=utf-8
from module.topic import topic
from flask import request
import json,func
from dao.DAO import DAO
from module.GlobalData import *
from module import GlobalData
from nlp.HanlpClient import HanlpClient
import requests
from bs4 import BeautifulSoup
import datetime
from snownlp import SnowNLP
@topic.route('/add/<table>',methods=['POST'])
def add(table):
    dao = DAO(table=table)
    result = {}
    vo = json.loads(func.get_param('vo','{}'))
    rowkey = func.get_param('rowkey','')
    uptime = func.get_param('uptime','false')
    uptime = True if uptime == 'true' else False
    oldvo = dao.loadone(id=rowkey)
    insert = False
    if oldvo==None or len(oldvo)==0:
        vo['createtime'] = func.get_time_stamp()
        vo['updatetime'] = func.get_time_stamp()
        rowkey = func.UUID()
        vo['id'] = rowkey
        insert = True
    if uptime:
        vo['updatetime'] = func.get_time_stamp()
    if not insert:
        dao.update(rowkey=rowkey,**vo)
    else:
        dao.insert(**vo)
    result['errorCode'] = 0
    result['message'] = '保存成功'
    result['rowkey'] = rowkey
    dao.close()
    return func.obj_to_jsonstr(result)

@topic.route('/load/<table>')
def load(table):
    rowkey = func.get_param('rowkey','')
    if len(rowkey)==0:
        result = api_result(ROWKEY_EMPTY,'参数为空')
    else:
        dao = DAO(table)
        item = dao.loadone(id=rowkey)
        result = api_result(REQUEST_SUCCESS,item=item)
        dao.close()
    return func.obj_to_jsonstr(result)
@topic.route('/count/<table>')
def count(table):
    topic = func.get_param('topic','')
    if len(topic)>0:
        dao = DAO(table)
        count = dao.count(topic=topic)
        dao.close()
        result = api_result(REQUEST_SUCCESS,count=count,topic=topic)
    else:
        result = api_result(ROWKEY_EMPTY,'参数为空')
    return func.obj_to_jsonstr(result)
@topic.route('/remove/<table>')
def remove(table):
    rowkey = func.get_param('rowkey','')
    if len(rowkey)==0 or len(table)==0:
        result = api_result(ROWKEY_EMPTY,'参数不完整')
    else:
        dao = DAO(table)
        dao.remove(id=rowkey)
        result=api_result(REQUEST_SUCCESS,message='删除成功')
        dao.close()
    return func.obj_to_jsonstr(result)
def is_admin():
    admin_clients = ['192.168.12.103','192.168.12.102']
    addr = func.getHeader('X-Real-IP')
    if addr == None:
        addr = request.remote_addr
    return addr in admin_clients
@topic.route('/list/<table>')
def topiclist(table):
    param = json.loads(func.get_param('param','{}'))
    pageno = int(func.get_param('pageno','1'))
    pagesize = int(func.get_param('pagesize','20'))
    order_key = func.get_param('orderkey','updatetime')
    order_desc = func.get_param('desc','true')
    order_desc = True if order_desc=='true' else False
    start = (pageno-1)*pagesize
    dao = DAO(table)
    items = dao.load(start=start,limit=pagesize,orderby=order_key,desc=order_desc,**param)
    total = dao.count(**param)
    totalPage = int((total/pagesize)+1)
    sentiment = func.get_param('sentiment','')
    if len(sentiment)>0:
        for item in items:
            item['sentiment'] = calc_text_sentiment(item[sentiment])
    result = api_result(REQUEST_SUCCESS,
                        items=items,
                        total=total,
                        pageno=pageno,
                        totalPage=totalPage,
                        pagesize=pagesize,admin=is_admin())
    return func.obj_to_jsonstr(result)


@topic.route('/sentiment/<table>')
def sentiment(table):
    rowkey = func.get_param('rowkey','')
    field = func.get_param('field','content')
    dao = DAO(table)
    item = dao.loadone(id=rowkey)
    content = item[field]
    subject = item['subject']
    sentiment = calc_text_sentiment(subject+'。'+content)
    result = {'errorCode':0,'rowkey':rowkey,'sentiment':sentiment}
    return func.obj_to_jsonstr(result)
def calc_text_sentiment(text):
    try:
        text = func.filter_tags(text)
        if len(text)>0:
            s = SnowNLP(text)
            return s.sentiments
        else:
            return 0.0
    except Exception as ex:
        print(ex)
        return 0.0
@topic.route('/contentEntityTags',methods=['POST'])
def content_entity_tags():
    content = func.get_param('content','')
    if len(content)==0:
        return api_result(ROWKEY_EMPTY,'内容为空')
    else:
        hanlp = HanlpClient()
        content = hanlp.filter_tags(content)
        result = hanlp.recognize_content(content)
        result['errorCode'] = 0
    return func.obj_to_jsonstr(result)

@topic.route('/parseBaikeContent')
def parse_baike_content():
    item = func.get_param('item','')
    if len(item)==0:
        result = api_result(ROWKEY_EMPTY,'内容为空')
    else:
        content = parse_baike(item)
        if len(content)>0:
            result=api_result(REQUEST_SUCCESS,content=content)
        else:
            result = api_result(ROWKEY_EMPTY,'百度百科没有收录'+item+'实体说明')
    return func.obj_to_jsonstr(result)
@topic.route('/uploadImage',methods=['POST'],strict_slashes=False)
def upload():
    def allowed_file(filename):
        ALLOWED_EXTENSIONS = set(['jpg', 'jpeg', 'png', 'PNG', 'JPG', 'JPEG'])
        return '.' in filename and filename.split('.', 1)[1] in ALLOWED_EXTENSIONS

    f = request.files['file'] if 'file' in request.files else None
    result = {}
    if f and allowed_file(f.filename):
        ext_name = f.filename.split('.', 1)[1]
        path = GlobalData.upload_path
        fname = str(func.get_time_stamp()) + '.' + ext_name
        fn = os.path.join(path,fname)
        f.save(fn)
        web_path = GlobalData.APP_CONTEXT_PATH+'/upload/'+fname
        result['location'] = web_path
        result['type'] = 'image'
        result['error'] = False
    else:
        result['location'] = ''
        result['type'] = 'image'
        result['error'] = True
    return func.obj_to_jsonstr(result)

def parse_baike(item):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36'}
    headers['Cookie'] = 'BIDUPSID=; BAIDUID=;'
    url = "https://baike.baidu.com/item/"+item
    s = requests.session()
    s.keep_alive = False  # 关闭多余连接
    req = s.get(url=url, headers=headers, verify=False)
    content = req.content
    soup = BeautifulSoup(content, "lxml")
    [s.extract() for s in soup(['style', 'img'])]
    basicInfo_block = soup.find(class_='lemma-summary')
    content = ""
    if basicInfo_block is not None:
        content = basicInfo_block.find(class_='para').get_text()
    req.close()
    s.close()
    return content
@topic.route('/getHistoryEvent')
def get_month_history_event():
    today = func.get_param('today','')
    if today=='':
        today = datetime.datetime.today().strftime('%m-%d')
    ds = today.split("-")
    dao = DAO(table='history_event')
    timestamp = func.get_time_stamp()
    item = dao.loadone(month=ds[0])
    if item==None or len(item)==0:
        dataURL = "https://baike.baidu.com/cms/home/eventsOnHistory/"+ds[0]+".json"
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36'}
        headers['Cookie'] = 'BIDUPSID=; BAIDUID=;'
        s = requests.session()
        s.keep_alive = False  # 关闭多余连接
        req = s.get(url=dataURL, headers=headers, verify=False)
        content = req.content
        dao.insert(id=func.UUID(),month=ds[0],content=content,updatetime=timestamp)
    else:
        content = item['content']
    result = api_result(REQUEST_SUCCESS,item=json.loads(content),today=today,key=today.replace('-',''))
    return func.obj_to_jsonstr(result)


if __name__=="__main__":
    print(get_month_history_event())